import mongoose from 'mongoose';
import bcrypt from 'bcryptjs';

// 生成ObjectId方法
const generateId = () => new mongoose.Types.ObjectId();

// 加密密码的方法
const hashPassword = async (password: string): Promise<string> => {
  const salt = await bcrypt.genSalt(10);
  return bcrypt.hash(password, salt);
};

// 预先生成ID，用于关联数据
const adminId = generateId();
const merchantId = generateId();
const user1Id = generateId();
const user2Id = generateId();

const category1Id = generateId();
const category2Id = generateId();
const category3Id = generateId();

const product1Id = generateId();
const product2Id = generateId();
const product3Id = generateId();
const product4Id = generateId();

const coupon1Id = generateId();
const coupon2Id = generateId();

const order1Id = generateId();

// 生成种子数据
export const generateSeedData = async () => {
  // 加密默认密码
  const password = await hashPassword('password123');

  // 用户数据
  const users = [
    {
      _id: adminId,
      name: '系统管理员',
      email: 'admin@example.com',
      password,
      phone: '13800138000',
      role: 'admin',
      isActive: true,
      addresses: [
        {
          name: '系统管理员',
          phone: '13800138000',
          province: '北京市',
          city: '北京市',
          district: '海淀区',
          address: '中关村科技园1号楼',
          isDefault: true,
        },
      ],
      createdAt: new Date(),
      updatedAt: new Date(),
    },
    {
      _id: merchantId,
      name: '官方商家',
      email: 'merchant@example.com',
      password,
      phone: '13900139000',
      role: 'merchant',
      isActive: true,
      addresses: [
        {
          name: '官方商家',
          phone: '13900139000',
          province: '北京市',
          city: '北京市',
          district: '朝阳区',
          address: '朝阳门外大街1号',
          isDefault: true,
        },
      ],
      createdAt: new Date(),
      updatedAt: new Date(),
    },
    {
      _id: user1Id,
      name: '测试用户1',
      email: 'user1@example.com',
      password,
      phone: '13700137000',
      role: 'customer',
      isActive: true,
      addresses: [
        {
          name: '测试用户1',
          phone: '13700137000',
          province: '上海市',
          city: '上海市',
          district: '浦东新区',
          address: '陆家嘴金融中心',
          isDefault: true,
        },
      ],
      createdAt: new Date(),
      updatedAt: new Date(),
    },
    {
      _id: user2Id,
      name: '测试用户2',
      email: 'user2@example.com',
      password,
      phone: '13600136000',
      role: 'customer',
      isActive: true,
      addresses: [
        {
          name: '测试用户2',
          phone: '13600136000',
          province: '广东省',
          city: '深圳市',
          district: '南山区',
          address: '科技园2号楼',
          isDefault: true,
        },
      ],
      createdAt: new Date(),
      updatedAt: new Date(),
    },
  ];

  // 分类数据
  const categories = [
    {
      _id: category1Id,
      name: '手机数码',
      description: '手机、平板、笔记本等数码产品',
      level: 1,
      path: category1Id.toString(),
      icon: 'phone',
      image: 'https://via.placeholder.com/200x200?text=Digital',
      isActive: true,
      order: 1,
      createdAt: new Date(),
      updatedAt: new Date(),
    },
    {
      _id: category2Id,
      name: '家用电器',
      description: '电视、冰箱、洗衣机等家用电器',
      level: 1,
      path: category2Id.toString(),
      icon: 'tv',
      image: 'https://via.placeholder.com/200x200?text=Appliance',
      isActive: true,
      order: 2,
      createdAt: new Date(),
      updatedAt: new Date(),
    },
    {
      _id: category3Id,
      name: '智能手机',
      description: '各品牌智能手机',
      parent: category1Id,
      level: 2,
      path: `${category1Id.toString()},${category3Id.toString()}`,
      icon: 'smartphone',
      image: 'https://via.placeholder.com/200x200?text=Smartphone',
      isActive: true,
      order: 1,
      createdAt: new Date(),
      updatedAt: new Date(),
    },
  ];

  // 商品数据
  const products = [
    {
      _id: product1Id,
      name: '高端智能手机 Pro',
      description: '最新款高端智能手机，配备顶级处理器和相机系统',
      price: 6999,
      originalPrice: 7999,
      stock: 100,
      images: [
        'https://via.placeholder.com/800x800?text=Phone1',
        'https://via.placeholder.com/800x800?text=Phone1-2',
      ],
      category: category3Id,
      merchant: merchantId,
      brand: '品牌A',
      attributes: {
        color: '黑色',
        memory: '8GB',
        storage: '256GB',
      },
      specifications: {
        screen: '6.7英寸 OLED',
        processor: '高通骁龙 8 Gen 2',
        camera: '5000万像素主摄',
        battery: '5000mAh',
      },
      salesCount: 0,
      rating: 5,
      reviews: [],
      isActive: true,
      tags: ['新品', '热销', '旗舰'],
      createdAt: new Date(),
      updatedAt: new Date(),
    },
    {
      _id: product2Id,
      name: '中端智能手机 Lite',
      description: '性价比极高的中端智能手机，满足日常使用需求',
      price: 2999,
      originalPrice: 3499,
      stock: 200,
      images: [
        'https://via.placeholder.com/800x800?text=Phone2',
        'https://via.placeholder.com/800x800?text=Phone2-2',
      ],
      category: category3Id,
      merchant: merchantId,
      brand: '品牌B',
      attributes: {
        color: '蓝色',
        memory: '6GB',
        storage: '128GB',
      },
      specifications: {
        screen: '6.5英寸 LCD',
        processor: '高通骁龙 778G',
        camera: '4800万像素主摄',
        battery: '4500mAh',
      },
      salesCount: 0,
      rating: 4.5,
      reviews: [],
      isActive: true,
      tags: ['性价比', '中端'],
      createdAt: new Date(),
      updatedAt: new Date(),
    },
    {
      _id: product3Id,
      name: '4K 超高清智能电视',
      description: '65英寸4K超高清智能电视，搭载最新操作系统',
      price: 5999,
      originalPrice: 6999,
      stock: 50,
      images: [
        'https://via.placeholder.com/800x450?text=TV',
        'https://via.placeholder.com/800x450?text=TV-2',
      ],
      category: category2Id,
      merchant: merchantId,
      brand: '品牌C',
      attributes: {
        size: '65英寸',
        resolution: '4K',
      },
      specifications: {
        screen: '65英寸 4K',
        processor: '四核处理器',
        ports: 'HDMI x3, USB x2',
        sound: '双扬声器 20W',
      },
      salesCount: 0,
      rating: 4.8,
      reviews: [],
      isActive: true,
      tags: ['4K', '智能', '大屏'],
      createdAt: new Date(),
      updatedAt: new Date(),
    },
    {
      _id: product4Id,
      name: '智能冰箱',
      description: '智能无霜冰箱，大容量，节能环保',
      price: 4999,
      originalPrice: 5999,
      stock: 30,
      images: [
        'https://via.placeholder.com/800x1000?text=Fridge',
        'https://via.placeholder.com/800x1000?text=Fridge-2',
      ],
      category: category2Id,
      merchant: merchantId,
      brand: '品牌D',
      attributes: {
        color: '银色',
        capacity: '450L',
      },
      specifications: {
        capacity: '450L',
        doorType: '对开门',
        energyClass: 'A++',
        features: '智能控温、APP控制',
      },
      salesCount: 0,
      rating: 4.7,
      reviews: [],
      isActive: true,
      tags: ['智能', '大容量', '节能'],
      createdAt: new Date(),
      updatedAt: new Date(),
    },
  ];

  // 优惠券数据
  const coupons = [
    {
      _id: coupon1Id,
      code: 'WELCOME2023',
      name: '新人专享券',
      description: '新用户注册专享优惠券',
      type: 'percentage',
      value: 10, // 10%折扣
      minPurchase: 100,
      maxDiscount: 50,
      startDate: new Date(),
      endDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30天后过期
      isActive: true,
      usageLimit: 1000,
      usageCount: 0,
      categories: [],
      products: [],
      excludedProducts: [],
      userRestriction: 'new',
      createdAt: new Date(),
      updatedAt: new Date(),
    },
    {
      _id: coupon2Id,
      code: 'DIGITAL50',
      name: '数码专享券',
      description: '数码产品满减优惠',
      type: 'fixed',
      value: 50, // 满减50元
      minPurchase: 1000,
      maxDiscount: 50,
      startDate: new Date(),
      endDate: new Date(Date.now() + 15 * 24 * 60 * 60 * 1000), // 15天后过期
      isActive: true,
      usageLimit: 500,
      usageCount: 0,
      categories: [category1Id],
      products: [],
      excludedProducts: [],
      userRestriction: 'all',
      createdAt: new Date(),
      updatedAt: new Date(),
    },
  ];

  // 订单数据
  const orders = [
    {
      _id: order1Id,
      orderNumber: 'O2305261234567890',
      user: user1Id,
      items: [
        {
          product: product1Id,
          quantity: 1,
          price: 6999,
          attributes: {
            color: '黑色',
            memory: '8GB',
            storage: '256GB',
          },
          name: '高端智能手机 Pro',
          image: 'https://via.placeholder.com/800x800?text=Phone1',
        },
      ],
      totalPrice: 6999,
      status: 'delivered',
      paymentMethod: 'alipay',
      paymentStatus: 'paid',
      paymentId: 'pay_123456789',
      shippingAddress: {
        name: '测试用户1',
        phone: '13700137000',
        province: '上海市',
        city: '上海市',
        district: '浦东新区',
        address: '陆家嘴金融中心',
        zipcode: '200120',
      },
      shippingMethod: '普通快递',
      shippingFee: 0,
      shippingCompany: '顺丰速运',
      trackingNumber: 'SF1234567890',
      discount: 0,
      note: '',
      refundReason: '',
      createdAt: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000), // 10天前
      updatedAt: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), // 7天前
      paidAt: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000), // 10天前
      shippedAt: new Date(Date.now() - 9 * 24 * 60 * 60 * 1000), // 9天前
      deliveredAt: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), // 7天前
    },
  ];

  return {
    users,
    categories,
    products,
    coupons,
    orders,
  };
};

// 导出MongoDB导入脚本
export const generateMongoImport = async () => {
  const data = await generateSeedData();
  
  // 为每个集合生成导入命令
  const collections = [
    { name: 'users', data: data.users },
    { name: 'categories', data: data.categories },
    { name: 'products', data: data.products },
    { name: 'coupons', data: data.coupons },
    { name: 'orders', data: data.orders },
  ];
  
  let importScript = '#!/bin/bash\n\n';
  importScript += '# MongoDB导入脚本\n';
  importScript += '# 使用方法: 确保mongoimport命令可用，然后运行此脚本\n\n';
  
  for (const collection of collections) {
    const fileName = `${collection.name}.json`;
    importScript += `echo "导入${collection.name}数据..."\n`;
    importScript += `mongoimport --db ecommerce --collection ${collection.name} --file ${fileName} --jsonArray --drop\n\n`;
    
    // 将数据写入JSON文件
    const fs = require('fs');
    const path = require('path');
    const filePath = path.join(__dirname, fileName);
    fs.writeFileSync(filePath, JSON.stringify(collection.data, null, 2));
  }
  
  // 将导入脚本写入文件
  const fs = require('fs');
  const path = require('path');
  const scriptPath = path.join(__dirname, 'import.sh');
  fs.writeFileSync(scriptPath, importScript);
  fs.chmodSync(scriptPath, '755'); // 添加执行权限
  
  return '导入数据已生成。运行 ./import.sh 导入数据到MongoDB。';
};

// 导入数据的方法
export const importData = async () => {
  const data = await generateSeedData();
  
  try {
    // 导入所有模型
    const { User, Category, Product, Coupon, Order } = require('../models');
    
    // 清空现有数据
    await User.deleteMany({});
    await Category.deleteMany({});
    await Product.deleteMany({});
    await Coupon.deleteMany({});
    await Order.deleteMany({});
    
    // 导入新数据
    await User.insertMany(data.users);
    await Category.insertMany(data.categories);
    await Product.insertMany(data.products);
    await Coupon.insertMany(data.coupons);
    await Order.insertMany(data.orders);
    
    console.log('数据导入成功！');
    return true;
  } catch (error) {
    console.error('数据导入失败:', error);
    return false;
  }
};

export default {
  generateSeedData,
  generateMongoImport,
  importData,
}; 